import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { useSelector } from "react-redux"
import type { ROOTSTATE } from "../Store"
import { useEffect, useState } from "react"
import { type IEditorConfig, type IDomEditor, type IToolbarConfig } from "@wangeditor/editor"
import type { RESPONSE } from "../types/base"
import { Editor, Toolbar } from "@wangeditor/editor-for-react"
import { Button, Flex, Form, Input, message, Select } from "antd"
import { Title } from "../components/Content/title"
import { useForm, type FormProps } from 'antd/es/form/Form'
import type { Issue, IssueForm } from '../api/type/issueType'
import { reqAddIssue } from '../api/issueApi'
import { useNavigate } from 'react-router'
export const IssueEdit = () => {
    const typeList = useSelector((state: ROOTSTATE) => state.typeStore.typeList)
    const user = useSelector((state: ROOTSTATE) => state.userStore.user)
    let [fromIssue] = useForm();
    const [messageAPI, contestHolder] = message.useMessage();
    const navigate = useNavigate()
    const issueFinish: FormProps<IssueForm>['onFinish'] = async (values) => {
        console.log('Success:', values);
        
        const { code } = await reqAddIssue({ title: values.title, content: html, typeId: values.typeId, userId: user._id! })
        if (code == 0) {
            messageAPI.success("发布成功")
            fromIssue.resetFields()
            navigate("/issue")
            
        }else{
            messageAPI.error("发布失败")
            fromIssue.resetFields()
        }
    };
    const options = typeList.map((item) => {
        return {
            value: item._id,
            label: item.typename
        }
    })
    //富文本
    //editor实例
    const [editor, setEditor] = useState<IDomEditor | null>(null)
    //编译器内容
    const [html, setHtml] = useState("<p>hello</p>")
    //工具栏配置
    const toolbarConfig: Partial<IToolbarConfig> = {}
    //编译器配置
    type InsertFnType = (
        url: string,
        alt: string | null,
        href: string | null
    ) => void
    const editorConfig: Partial<IEditorConfig> = {
        MENU_CONF: {
            uploadImage: {
                fieldName: "file",
                server: "/dev-api/api/upload",
                customInsert(res: RESPONSE<string>, insertFn: InsertFnType) {
                    insertFn(res.data, "", "")
                },

            }
        },
        placeholder: "请输入内容..."
    }
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])

    return (
        <>
            {contestHolder}
            <Flex vertical gap={30}>
                <Title title="提问模块"></Title>
                <Form
                    layout="vertical"
                    onFinish={issueFinish}
                    form={fromIssue}
                >
                    <Form.Item
                        label="文章标题"
                        name="title"
                        rules={[
                            { required: true, message: "填写文章标题" },
                            { max: 50, message: "最大长度未50" },
                        ]}
                    >
                        <Input></Input>

                    </Form.Item>

                    <Form.Item
                        label="文章类别"
                        name="typeId"
                        rules={[
                            { required: true, message: "选择文章类别" },

                        ]}
                    >
                        <Select options={options} style={{ width: 150 }}></Select>

                    </Form.Item>

                    <Form.Item
                        label="文章内容"
                    >
                        <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
                            <Toolbar
                                editor={editor}
                                defaultConfig={toolbarConfig}
                                mode="default"
                                style={{ borderBottom: "1px solid #ccc" }}
                            ></Toolbar>
                            <Editor
                                defaultConfig={editorConfig}
                                value={html}
                                onCreated={setEditor}
                                onChange={(editor) => setHtml(editor.getHtml())}
                                mode="default"
                                style={{ height: "500px", overflowY: "hidden" }}>

                            </Editor>
                        </div>

                    </Form.Item>
                    <Form.Item label={null}>
                        <Flex gap={30}>

                            <Button type="primary" htmlType="submit">确定发布</Button>
                            <Button onClick={() => {
                                //重置表单内容
                                fromIssue.resetFields();
                            }}>重置</Button>
                        </Flex>
                    </Form.Item>


                </Form>
            </Flex>
        </>
    )
}